#include<libserv/libserv_message.h>
#include <cstring>
#include <utility>
#include <iostream>

namespace libserv {


    bool check_package(std::vector<char> package) {
        int check = (int) package[package.size() - 1];
        int sum = 0;
        for (int i = 0; i < package.size() - 2; i++) {
            sum += package[i];
        }
        return check == sum;
    }

    Message::Message(unsigned char head, int max_queue_size) : BaseMessage(max_queue_size), head(head),
                                                               check_function(check_package) {

    }

    void Message::BindPackageCheck(bool(*check_function)(std::vector<char>)) {
        this->check_function = check_function;
    }

    void Message::SerialRecive(char buffer) {
        if (this->prepare_message.empty()) {
            if (buffer != this->head)
                return;
            this->prepare_message.push_back(buffer);
        } else {
            if (buffer == this->head) {
                if (this->check_function(this->prepare_message))
                    this->push_message(this->prepare_message);
                this->prepare_message.clear();
                this->prepare_message.push_back(buffer);
            } else {
                this->prepare_message.push_back(buffer);
            }
        }
    }

    bool Message::IsEmpty() {
        return (this->size_message() == 0);
    }

    Message::~Message() {

    }

}